package cn.daixi.web.sys.controller;


import cn.daixi.web.sys.dto.LoginReq;
import cn.daixi.web.sys.dto.RegisterReq;
import cn.daixi.web.sys.entity.User;
import cn.daixi.web.sys.service.UserService;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/sys/user")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("findById")
    public User findById(@RequestParam("id") Long id){
        return userService.findById(id);
    }

    @PostMapping("login")
    public User login(@Validated @RequestBody LoginReq loginReq, HttpServletResponse response){
        User user = userService.login(loginReq);
        Cookie cookie = userService.setLogin(user);
        response.addCookie(cookie);
        return user;
    }

    @PostMapping("register")
    public User register(@Validated @RequestBody RegisterReq registerReq, HttpServletResponse response){
        User user = userService.register(registerReq);
        Cookie cookie = userService.setLogin(user);
        response.addCookie(cookie);
        return user;
    }

    @PostMapping("list")
    public List<User> list(){
        return userService.list();
    }
}
